<?php

namespace Module\Work\Util;

use ModStart\Core\Assets\AssetsUtil;
use ModStart\Core\Dao\ModelUtil;
use Illuminate\Database\Eloquent\Model;
use Module\Vendor\Util\CacheUtil;
use Module\Work\Model\Work;

class WorkUtil
{
    const CACHE_KEY_PREFIX = 'Work:';

    public static function clearCache()
    {
        $records = Work::all(['id', 'name']);
        foreach ($records as $record) {
            CacheUtil::forget(self::CACHE_KEY_PREFIX . 'Id:' . $record->id);
            CacheUtil::forget(self::CACHE_KEY_PREFIX . 'Name:' . $record->name);
            CacheUtil::forget(self::CACHE_KEY_PREFIX . 'Name:' . $record->name . ':All');
        }
    }
    public static function get($id)
    {
        return ModelUtil::get(Work::class, $id);
    }

    public static function update($id, $data)
    {
        return ModelUtil::update(Work::class, $id, $data);
    }

    public static function all()
    {
        return ModelUtil::all(Work::class, [], ['*'], ['sort', 'asc']);
    }

    public static function latest($limit = 5)
    {
        return ModelUtil::model(Work::class)
            ->orderBy('id', 'desc')
            ->limit($limit)->get()->toArray();
    }

    public static function buildRecord($record)
    {
        $record['cover'] = AssetsUtil::fixFull($record['cover']);
        return $record;
    }

    public static function buildRecords($records)
    {
        foreach ($records as $k => $v) {
            $records[$k] = self::buildRecord($v);
        }
        return $records;
    }
}
